package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.data.support.SqlWithParams;
import com.authine.cloudpivot.ext.applicationservice.base.ApplicationBaseService;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.InviteCode;
import com.authine.cloudpivot.ext.dto.OrganizationCode;
import com.authine.cloudpivot.ext.utils.BoServiceUtils;
import com.authine.cloudpivot.ext.utils.premission.PermissionUtils;
import com.authine.cloudpivot.ext.utils.system.OrgUtils;
import com.authine.common.json.JsonUtils;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.ws.rs.POST;
import javax.ws.rs.Path;

import java.util.*;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

@Path("InvitecodeService")
@Slf4j
public class InvitecodeService extends ApplicationBaseService {
    private NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);

    @Path("createNum")
    @POST
    @Operation(summary = "组织邀请码-新增组织邀请码", tags = CUSTOM_SERVICE)
    public SingleResponse<BO> createNum(@Parameter InviteCode invitecode) {
        log.info("------------------------createNum---------------", JSONObject.toJSONString(invitecode));
        if (null == invitecode.getNum()) {
            return SingleResponse.buildFailure("-1", "创建数量必填");
        }
        if (null == invitecode.getExpire()) {
            return SingleResponse.buildFailure("-1", "有效日期必填");
        }
        List<Map<String, Object>> data = new ArrayList<>();
        for (int i = 0; i < invitecode.getNum(); i++) {
            Map<String, Object> maps = Maps.newHashMap();
            SelectorFormat org = OrgUtils.getOrgByUserId().createSelectorFormat();
            maps.put("expire", invitecode.getExpire());
            maps.put("code", genRandomNum());
            maps.put("customer_organization_name", org.getName());
            maps.put("customer_organization_id", org);
            maps.put("vendor_organization_id", null);
            data.add(maps);
        }
        SingleResponse<BO> bo = BoServiceUtils.createBo(ModelConst.T_ORGANIZATION_INVITE_CODE, data);
        return bo;
    }

    /**
     * 供应商邀请码列表
     */
    @Path("orgInviteCodeList")
    @POST
    @Operation(summary = "供应商邀请码列表",tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> orgInviteCodeList(@Parameter OrganizationCode dto){
        log.info("----------------供应商邀请码列表  orgInviteCodeList-----------------", JSONObject.toJSONString(dto));
        if(null == dto.getPageIndex() || null == dto.getPageSize()){
            return SingleResponse.buildFailure("-1","参数不合法");
        }
        String tableName = getTableName(ModelConst.T_ORGANIZATION_INVITE_CODE);
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("select * from "+tableName+
                " where deleted = '0' and vendor_organization_id is not null and vendor_organization_id <> ''");
        countSql.append("select count(*) from "+tableName+
                " where deleted = '0' and vendor_organization_id is not null and vendor_organization_id <> ''");
        //拼接参数
        if (StringUtils.isNotBlank(dto.getCustomerOrganizationName())) {
            whereSql.append(" and customer_organization_name like :customer_organization_name ");
            parameter.put("customer_organization_name", "%" + dto.getCustomerOrganizationName() + "%");
        }
        if (StringUtils.isNotBlank(dto.getVendorOrganizationName())) {
            whereSql.append(" and vendor_organization_name like :vendor_organization_name ");
            parameter.put("vendor_organization_name", "%" + dto.getVendorOrganizationName() + "%");
        }
        // 拼接权限sql
        SqlWithParams inviteCodePermissionSql = PermissionUtils.permissionSql(ModelConst.T_ORGANIZATION_INVITE_CODE, ModelConst.T_ORGANIZATION_INVITE_CODE, null);
        log.info("------------------------供应商邀请码权限sql：{}------------------------", JSONObject.toJSONString(inviteCodePermissionSql));
        if (inviteCodePermissionSql != null && !org.springframework.util.StringUtils.isEmpty(inviteCodePermissionSql.getSql())) {
            whereSql.append("and ").append(inviteCodePermissionSql.getSql()).append("\n");
            parameter.putAll(inviteCodePermissionSql.getParams());
        }
        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" order by createdTime desc");
        listSql.append(" limit " + dto.getPageIndex()*dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------供应商邀请码列表 orgInviteCodeList listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        //构建结果集
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_ORGANIZATION_INVITE_CODE);
        return SingleResponse.of(bOList);
    }

    private String genRandomNum() {

        int i;
        int count = 0;
        char[] str = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
                'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        StringBuffer pwd = new StringBuffer("");
        Random r = new Random();
        while (count < 8) {
            i = Math.abs(r.nextInt(str.length));
            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count++;
            }
        }
        return pwd.toString();

    }

}
